package com.lee.mq.demo;

import com.lee.mq.common.Consumer;
import com.lee.mq.common.MqException;
import com.lee.mq.mqclient.Channel;
import com.lee.mq.mqclient.Connection;
import com.lee.mq.mqclient.ConnectionFactory;
import com.lee.mq.mqserver.core.BasicProperties;
import com.lee.mq.mqserver.core.ExchangeType;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-11-02
 * Time: 20:00
 */
public class DemoConsumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("消费者启动！");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(9090);
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

//        boolean ok = channel.exchangeDeclare("exchange1", ExchangeType.DIRECT,true,false,null);
//        System.out.println("交换机创建："+ok);
//        boolean ok = channel.exchangeDeclare("exchange1",ExchangeType.FANOUT,true,false,null);
//        System.out.println("创建交换机："+ok);
//
//        // 创建队列
//        ok = channel.queueDeclare("queue1",true,false,false,null);
//        System.out.println("创建队列1："+ok);
//        ok = channel.queueDeclare("queue2",true,false,false,null);
//        System.out.println("创建队列2："+ok);

        boolean ok = channel.exchangeDeclare("exchange1", ExchangeType.TOPIC,true,false,null);
        System.out.println("交换机创建："+ok);
        // 创建队列
        ok = channel.queueDeclare("queue1",true,false,false,null);
        System.out.println("创建队列1："+ok);
        // 创建绑定
        ok = channel.queueBind("exchange1","queue1","aaa.bbb.ccc");
        System.out.println("创建绑定："+ok);

        channel.basicConsume("queue1", false, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("消费消息开始!");
                System.out.println("消息Id："+basicProperties.getMessageId()+ ", 消息内容："+new String(body,0,body.length));
                System.out.println("消费消息结束!");
                boolean ok = channel.basicAck("queue1",basicProperties.getMessageId());
                System.out.println("消息："+basicProperties.getMessageId()+" 应答："+ok);
            }
        });

        while (true) {
            Thread.sleep(500);
        }
    }

}
